﻿using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Project.Core.Config.Common.Utils;
using System.Diagnostics;

namespace Project.Core.Config.Config.DbConnect {
    public static class BuilderDbExtensions {
        public static void AddDbBuilder(this WebApplicationBuilder builder) {

            Debug.WriteLine("配置数据库");
            // 获取外部程序集的文件名或路径
            //var assemblyNames = builder.Configuration.GetSection("ExternalAssembly").GetChildren().Select(x => x.Value).ToArray();
            var assemblyNames = AppHelper.ReadAppSettings("Db", new string[] { "ExternalAssembly" });
            //添加数据库服务
            builder.Services.AddDbContext<AppDbContext>(options =>
                //options.UseSqlServer(builder.Configuration.GetConnectionString("DBConnection"))
                options.UseMySql(
                    builder.Configuration.GetConnectionString("MySqlConnection"),
                    ServerVersion.AutoDetect(builder.Configuration.GetConnectionString("MySqlConnection"))
                )
            );
            builder.Services.AddScoped(p => {
                var options = p.GetService<DbContextOptions<AppDbContext>>();
                var names = assemblyNames;
                return new AppDbContext(options, names);
            });
        }
    }
}
